﻿var data; // The DataTable object containing all underlying data.
var monthview; // The DataView object exposing the underlying data for a specific month only.
var charts = []; // Associative array mapping all charts to their container id's.

$(document).ready(function () {
    $("#tabs").tabs();
    google.load("visualization", "1.0", { packages: ["corechart", "table"], callback: initDynamicContent });
});

function initDynamicContent() {
    // Load the statistics into JSON via AJAX.
    var jsonData = $.ajax({
        url: "statdata.aspx",
        dataType: "json",
        async: false
    }).responseText;

    // Put the statistics in the global DataTable object.
    data = new google.visualization.DataTable(jsonData);
    monthview = new google.visualization.DataView(data);
    monthview.setColumns([0, 3, 4, 5, 6, 7, 8, 9]);

    // Initialize the month input control.
    {
        var dateview = new google.visualization.DataView(data);
        dateview.setColumns([{ calc: makeDate, type: 'date'}]);
        var dates = dateview.getDistinctValues(0);
        var $month = $("select[name='month']");
        for (var i = 0; i < dates.length; i++)
            $month.append("<option value='" + dates[i].getFullYear() + " " + dates[i].getMonth() + "'>"
            + formatDate(dates[i]) + "</option>");
        $month.find("option").last().prop("selected", "selected");
    }
    // Filter rows according to the selected month.
    selectMonth();

    // Initialize all charts in ChartWrapper objects.
    charts["transchart"] = new google.visualization.ChartWrapper({
        chartType: "BarChart",
        dataTable: new google.visualization.DataView(monthview),
        options: { width: 750, height: 400, title: "Transaktioner og aktiveringer",
            hAxis: { title: "Antal", minValue: 0 }, fontName: '"Arial"'
        },
        containerId: "transchart"
    });
    charts["transchart"].getDataTable().setColumns([0, 1, 2]);

    charts["relchart"] = new google.visualization.ChartWrapper({
        chartType: "BarChart",
        dataTable: new google.visualization.DataView(monthview),
        options: { width: 750, height: 400, title: "Transaktioner og aktiveringer / 1000 borgere",
            hAxis: { title: "Antal", minValue: 0 }, fontName: '"Arial"'
        },
        containerId: "relchart"
    });
    charts["relchart"].getDataTable().setColumns([0, 5, 6]);

    charts["pctchart"] = new google.visualization.ChartWrapper({
        chartType: "BarChart",
        dataTable: new google.visualization.DataView(monthview),
        options: { width: 750, height: 400, title: "Gennemførselsprocent",
            hAxis: { title: "Procent", minValue: 0, maxValue: 100 }, fontName: '"Arial"'
        },
        containerId: "pctchart"
    });
    charts["pctchart"].getDataTable().setColumns([0, 3]);

    charts["timechart"] = new google.visualization.ChartWrapper({
        chartType: "BarChart",
        dataTable: new google.visualization.DataView(monthview),
        options: { width: 750, height: 400, title: "Gennemsnitlig gennemførselstid",
            hAxis: { title: "Sekunder", minValue: 0 }, fontName: '"Arial"'
        },
        containerId: "timechart"
    });
    charts["timechart"].getDataTable().setColumns([0, 4]);

    charts["table"] = new google.visualization.ChartWrapper({
        chartType: "Table",
        dataTable: monthview,
        options: { width: 950, height: 480 },
        containerId: "table"
    });

    // Initialize all input controls.
    $("select[name='sortby']").each(function () {
        for (var i = 0; i < monthview.getNumberOfColumns(); i++) {
            var label = monthview.getColumnLabel(i);
            $(this).append("<option value='" + i + "'>" + label + "</option>");
        }
    });
    $(".slider").slider({
        orientation: "vertical",
        min: 0,
        slide: function (event, ui) {
            var $tab = $(this).closest(".tab");
            $tab.find("select[name='rows'] option[value='"
                + ($(this).slider("option", "max") - ui.value) + "']")
                .prop("selected", true);
            updateChart($tab);
        }
    });
    updateInputControls();

    // Bind events for manipulating the charts' views of the data.
    $("select[name='month']").change(function () {
        selectMonth();
        updateInputControls();
        equalizeAxes();
        drawCharts();
    });
    $("select[name='sortby'], select[name='rows']").change(function () {
        updateChart($(this).closest(".tab"));
    });
    $("select[name='rows']").change(function () {
        var $slider = $(this).closest(".tab").find(".slider");
        $slider.slider("value", $slider.slider("option", "max") - parseInt($(this).val()));
    });

    // IE quickfix. Avoid drawing charts that are not visible.
    // Method drawCharts() has been changed to only draw the currently selected chart.
    $("#tabs").on("tabsselect", function (event, ui) {
        setTimeout(function () { updateChart($("#" + ui.panel.id)); }, 100);
    });

    equalizeAxes();
    drawCharts();
}

function updateInputControls() {
    $("select[name='rows']").each(function () {
        $(this).find("option").remove();
        for (var i = 0; i < monthview.getNumberOfRows() / 10; i++) {
            var range = (i * 10 + 1) + " - " + ((i + 1) * 10);
            $(this).append("<option value='" + i + "'>" + range + "</option>");
        }
    });
    $(".slider").slider("option", "max", Math.floor((monthview.getNumberOfRows() - 1) / 10))
        .slider("option", "value", Math.floor((monthview.getNumberOfRows() - 1) / 10));
}

function selectMonth() {
    var val = $("select[name='month']").val().split(" ");
    monthview.setRows(data.getFilteredRows([{ column: 1, value: parseInt(val[0]) },
    { column: 2, value: parseInt(val[1]) + 1}]));
}

function drawCharts() {
    updateChart($("#tabs > div.tab").eq($("#tabs").tabs("option", "selected")));
    //$(".tab").each(function () { updateChart($(this)); });
}

function updateChart($tab) {
    var id = $tab.find(".chart").attr("id");
    if (id != "table") {
        var sortby = parseInt($tab.find("select[name='sortby']").val());
        var rows = parseInt($tab.find("select[name='rows']").val());
        if (sortby != 0) sortby = { column: sortby, desc: true };
        charts[id].getDataTable().setRows(monthview.getSortedRows(sortby).slice(rows * 10, rows * 10 + 10));
    }
    charts[id].draw();
}

function equalizeAxes() {
    charts["transchart"].setOption("hAxis.maxValue", monthview.getValue(monthview.getSortedRows(2).pop(), 2));
    charts["relchart"].setOption("hAxis.maxValue", monthview.getValue(monthview.getSortedRows(6).pop(), 6));
    charts["timechart"].setOption("hAxis.maxValue", monthview.getValue(monthview.getSortedRows(4).pop(), 4));
}

function makeDate(dt, row) {
    return new Date(dt.getValue(row, 1), dt.getValue(row, 2) - 1);
}

function formatDate(date) {
    var yr = date.getFullYear();
    switch (date.getMonth()) {
        case 0: return "Januar " + yr;
        case 1: return "Februar " + yr;
        case 2: return "Marts " + yr;
        case 3: return "April " + yr;
        case 4: return "Maj " + yr;
        case 5: return "Juni " + yr;
        case 6: return "Juli " + yr;
        case 7: return "August " + yr;
        case 8: return "September " + yr;
        case 9: return "Oktober " + yr;
        case 10: return "November " + yr;
        case 11: return "December " + yr;
    }
}
